using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriviaController : MonoBehaviour
{
	public List<TriviaButton> buttons = new List<TriviaButton>();

	public UILabel questionLabel;

	public UILabel explanationLabel;

	public UIWidget mainWidget;

	public GameObject questionGO;

	public GameObject explanationGO;

	private TriviaQuestions.TriviaQuestion question;

	private bool inRequest;

	public void Show()
	{
		mainWidget.cachedGameObject.SetActive(true);
		ShowQuestion(TriviaQuestions.instance.RandomQuestion());
		StopAllCoroutines();
		StartCoroutine(DoFade(mainWidget.alpha, 1f, 0.5f, true));
	}

	public void Hide()
	{
		StopAllCoroutines();
		if (mainWidget.cachedGameObject.activeSelf)
		{
			StartCoroutine(DoFade(mainWidget.alpha, 0f, 0.5f, false));
		}
	}

	private IEnumerator DoFade(float from, float to, float duration, bool active)
	{
		float time = 0f;
		mainWidget.cachedGameObject.SetActive(true);
		while (time < duration)
		{
			time += Time.deltaTime;
			float alpha = Mathf.Lerp(from, to, time / duration);
			mainWidget.alpha = alpha;
			yield return null;
		}
		mainWidget.cachedGameObject.SetActive(active);
	}

	public void ShowQuestion(TriviaQuestions.TriviaQuestion question)
	{
		inRequest = false;
		questionGO.SetActive(true);
		explanationGO.SetActive(false);
		this.question = question;
		questionLabel.text = question.question;
		int num = 0;
		foreach (TriviaButton button in buttons)
		{
			if (num >= question.answers.Count)
			{
				button.Hide();
				continue;
			}
			string answer = question.answers[num];
			button.ShowAnswer(answer, num, OnClickDelegate);
			num++;
		}
	}

	public void ShowExplanation()
	{
		questionGO.SetActive(false);
		explanationGO.SetActive(true);
		explanationLabel.text = question.explanation;
		int num = 0;
		foreach (TriviaButton button in buttons)
		{
			button.Hide();
		}
		buttons[1].ShowText("Continue...", OnContinue);
	}

	private void OnContinue()
	{
		ShowQuestion(TriviaQuestions.instance.RandomQuestion());
	}

	private void OnClickDelegate(int answerIndex, TriviaButton button)
	{
		if (inRequest)
		{
			return;
		}
		inRequest = true;
		bool correctAnswer = question.correctAnswer == answerIndex;
		button.ShowAnswerAnim(correctAnswer, delegate
		{
			inRequest = false;
			if (correctAnswer)
			{
				if (!string.IsNullOrEmpty(question.explanation))
				{
					ShowExplanation();
				}
				else
				{
					ShowQuestion(TriviaQuestions.instance.RandomQuestion());
				}
			}
		});
	}
}
